<script setup lang="ts">
import {parseTime} from '@/utils/ruoyi'
import {getStudyList} from '@/api/study'

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const emits = defineEmits(['close'])

/*========================================>( 模型属性 )<========================================*/
//是否显示本modal
const show = ref<boolean>(false)

//历史数据同步任务是否执行中
const isHistorySyncRunning = ref<boolean>(false)

//历史数据同步任务:资源目录的数量
const historyResourceCount = ref<number>(0)

//历史数据同步任务:已同步资源的数量
const historyRecordCount = ref<number>(0)

//本日资源目录已同步的资源数量
const todayCount = ref<number>(0)

// const historyDataRate = ref<number>(0)

/*========================================>( 作用域属性 )<========================================*/
let _timer:any = undefined

/*========================================>( 计算属性 )<========================================*/
//历史同步任务的状态，0：未执行，1.已执行，2.执行中
const historySyncStatus = computed(()=>{
    if(historyResourceCount.value === 0){
        //目录数量为0，防止NAN错误，视为未执行
        return 0
    }
    if(historyResourceCount.value !== historyRecordCount.value){
        //同步为满足总数
        return isHistorySyncRunning.value?2:0
    }
    return 1
})

//历史同步任务的进度0-100
const historyDataRate = computed(()=>{
    if(historyResourceCount.value === 0){
        //目录数量为0，防止NAN错误，视为0进度
        return 0
    }
    return (historyRecordCount.value/historyResourceCount.value * 100).toFixed(2)
})

/*========================================>( 普通方法 )<========================================*/
const getTodayStudy = ()=>{
    //获取本日研究数量
    const todayDateStr = parseTime(new Date(),'{y}-{m}-{d}')
    getStudyList({date:todayDateStr}).then((e:any)=>{
        todayCount.value = e.rows.length
    })
}

//取消轮询
const cancelTaskOfHistoryStatus = () => {
    clearInterval(_timer)
    _timer = undefined
}

const startHistoryDataListener = async() => {
    const f = async()=>{
        const res = window.$.sendSync('TASK-STATUS-HISTORY')
        console.log('轮询结果',res)
        const {finishedCount, resourceCount,running,error} = res
        if(error){
            //获取历史同步状态出错，展示错误并取消轮询
            cancelTaskOfHistoryStatus()
            proxy?.$modal.alertError(error)
            return false
        }

        historyResourceCount.value = Number(resourceCount)
        historyRecordCount.value = Number(finishedCount)
        isHistorySyncRunning.value = running
        if(!running){
            //后台未执行任务，取消轮询
            cancelTaskOfHistoryStatus()
            return false
        }
        return true
    }
    if(await f()){
        _timer = setInterval(f,500)
    }
}

//获取资源目录监听任务状态

/*========================================>( 监听方法 )<========================================*/

const handleClose = (refresh:boolean) => {
    cancelTaskOfHistoryStatus()
    emits('close',{refresh})
}

const handleHistoryStartSync = () => {
    //开始历史数据同步
    proxy?.$modal.confirm('是否要同步历史影像资源？').then(()=>{
        //通知后台重新同步
        historyResourceCount.value = 0
        historyRecordCount.value = 0
        const {error} = window.$.sendSync('TASK-EXEC-HISTORY')
        console.log('执行同步任务返回',error)
        if(error){
            proxy?.$modal.alertError(error)
            return
        }
        startHistoryDataListener()
    })
}

const handleTodayStartSync = () => {
    //开始数据同步
    proxy?.$modal.confirm('是否要立即同步今日研究？').then(()=>{
        const {error} = window.$.sendSync('TASK-EXEC-TODAY')
        if(error){
            proxy?.$modal.alertError(error)
            return
        }
        proxy?.$modal.alertSuccess('同步成功')
        getTodayStudy()
    })
}

const handleFutureStartSync = () => {
    //开始数据同步
    proxy?.$modal.confirm('是否要开启资源监听任务？').then(()=>{
        const {error} = window.$.sendSync('TASK-EXEC-FUTURE')
        if(error){
            proxy?.$modal.alertError(error)
            return
        }
        proxy?.$modal.alertSuccess('开启成功')
        getTodayStudy()
    })
}

onMounted(()=>{

    //1.获取历史同步任务进度
    cancelTaskOfHistoryStatus()
    startHistoryDataListener()


    //2.获取本日同步数量
    getTodayStudy()

    
    const {listening} = window.$.sendSync('TASK-STATUS-FUTURE')



})

show.value = true
</script>
<template>
	<el-dialog v-model="show" title="数据同步中心" width="800" :close-on-click-modal="false" :show-close="false">
		<el-row :gutter="20">
			<el-col :span="8">
				<el-card style="max-width: 250px">
					<template #header>
						<div class="card-header" style="position:relative">
							<span>历史数据同步</span>
							<el-tag v-if="historySyncStatus === 2" type="primary" class="m-r-20-0">同步中</el-tag>
                            <!-- <el-tag v-if="historySyncStatus === 1" type="success" class="m-r-20-0">已同步</el-tag> -->
                            <el-tag v-if="historySyncStatus === 0" type="info" class="m-r-20-0">未同步</el-tag>
							<el-icon style="vertical-align: middle;position:absolute;top:2px;right:0;cursor: pointer;" @click="handleHistoryStartSync" v-if="historySyncStatus!==2">
								<Refresh />
							</el-icon>
						</div>
					</template>
					<div class="content">
						<el-progress
							:text-inside="true"
							:stroke-width="24"
							:percentage="historyDataRate"
							:color="historySyncStatus==1?'#99CC66':'#0099CC'"
							:striped="historySyncStatus==2"
							striped-flow
							:duration="10"
							:format="(e:number)=>e==100?'已完成':`${e}%`"
						/>
					</div>
				</el-card>
			</el-col>
			<el-col :span="8">
				<el-card style="max-width: 250px">
					<template #header>
						<div class="card-header" style="position:relative">
							<span>今日数据同步</span>
							<el-icon style="vertical-align: middle;position:absolute;top:2px;right:0;cursor: pointer;" @click="handleTodayStartSync">
								<Refresh />
							</el-icon>
						</div>
					</template>
					<div class="content">已同步，今日共{{todayCount}}例研究</div>
				</el-card>
			</el-col>
			<el-col :span="8">
				<el-card style="max-width: 250px">
					<template #header>
						<div class="card-header" style="position:relative">
							<span>新数据监听任务</span>
							<el-icon style="vertical-align: middle;position:absolute;top:2px;right:0;cursor: pointer;" @click="handleFutureStartSync">
								<Refresh />
							</el-icon>
						</div>
					</template>
					<div class="content">默认已开启</div>
				</el-card>
			</el-col>
		</el-row>

		<template #header>
			<div class="card-header">数据同步管理</div>
		</template>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="handleClose">关闭</el-button>
			</div>
		</template>
	</el-dialog>
</template>
<style lang="scss"></style>
<style lang="scss" scoped>
.content{
    width:100%;
    height:50px;
}
</style>
